package org.supper.auth.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.supper.auth.utils.JsonResult;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: huqi
 * @Date: 2021/3/15: 15:22
 * @Description:
 */
@Configuration
@Slf4j
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         org.springframework.security.core.AuthenticationException authException) throws ServletException {

            returnError(response,authException);
    }

    /**
     * 出现token失效的时候走此处
     * @param response
     * @throws ServletException
     */
    public void returnError(HttpServletResponse response,org.springframework.security.core.AuthenticationException authException)throws ServletException{
        try {
            response.setContentType("application/json,charset=utf-8");
            response.setStatus(200);
            ObjectMapper objectMapper = new ObjectMapper();
            // 无效token
            if (authException.getMessage().contains("Invalid access token")) {
                objectMapper.writeValue(response.getOutputStream(), JsonResult.fail("无效token","401"));
            } else {
                objectMapper.writeValue(response.getOutputStream(), JsonResult.fail("未配置接口授权规则或没有token","403"));
            }

        } catch (Exception e1) {
            throw new ServletException();
        }
    }
}


